from PySide6 import QtCore, QtGui, QtWidgets


import os
import sys
import requests

from ui_mainwindow import Ui_MainWindow
from ui_popmessage import Ui_PopMessage

class PopMessage(QtWidgets.QWidget):

    deleteMessage = QtCore.Signal(int)
    copyMessage = QtCore.Signal(str)

    def __init__(self, index, text, parent=None):
        super().__init__(parent)
        self.ui = Ui_PopMessage()
        self.ui.setupUi(self)
        
        self.ui.label.setWordWrap(True)
        self.ui.label.setText(text)
        self.ui.label.customContextMenuRequested.connect(self.label_menu_requested)

        self.setStyleSheet("""
            QLabel {
                background-color: #f0f0f0;
                border: 1px solid #d0d0d0;
                border-radius: 5px;
            }
            QLabel:hover {
                background-color: #e0e0e0;
            }
        """)

        self.index = index
        self.text = text

    def label_menu_requested(self, pos):
        self.menu = QtWidgets.QMenu()
        self.menu.addAction('删除', lambda: self.deleteMessage.emit(self.index))
        self.menu.addAction('复制', lambda: self.copyMessage.emit(self.text))
        self.menu.exec(QtGui.QCursor.pos())

        # self.copy = QtWidgets.QLabel('c', self.ui.label)
        # self.copy.setObjectName('copy')
        # self.copy.setFixedSize(25,25)
        # self.copy.clicked.connect(lambda: QtWidgets.QApplication.clipboard().setText(self.text))
        
    # def resizeEvent(self, event):
        # self.copy.move(self.ui.label.geometry().bottomRight() - self.copy.geometry().bottomRight())
        # return super().resizeEvent(event)

class HumanWantsWindow(QtWidgets.QMainWindow):
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.wants = []

        self.ui.list_wants.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection)
        self.ui.list_wants.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.DoubleClicked)
        self.ui.list_wants.setDragEnabled(True)
        self.ui.list_wants.viewport().setAcceptDrops(True)
        self.ui.list_wants.setDropIndicatorShown(True)
        self.ui.list_wants.setDragDropMode(QtWidgets.QAbstractItemView.DragDropMode.InternalMove)

        self.ui.scrollArea.horizontalScrollBar().setVisible(False)

        self.default_wants()
        self.update_list_wants()

    def default_wants(self):
        import json
        if os.path.exists('data/default.json'):
            with open('data/default.json', 'r') as f:
                self.wants = json.load(f)
        else:
            self.wants = []

    @QtCore.Slot(QtWidgets.QListWidgetItem,QtWidgets.QListWidgetItem)
    def on_list_wants_currentItemChanged(self, current:QtWidgets.QListWidgetItem, previous:QtWidgets.QListWidgetItem):
        
        while True:
            item = self.ui.frame.layout().takeAt(0)
            if item is None:
                break
            if item.widget():
                item.widget().deleteLater()            
            self.ui.frame.layout().removeItem(item)

        if not current:
            return

        texts = current.data(QtCore.Qt.ItemDataRole.UserRole + 1)
        for index, text in enumerate(texts):
            self.append_answare_widget(index, text)

        layout: QtWidgets.QVBoxLayout =  self.ui.frame.layout()
        layout.addStretch()
        
    @QtCore.Slot()
    def on_btn_add_want_clicked(self):
        self.wants.append({
            'title':'新的想法',
            'answers': []
        })
        self.update_list_wants()

    @QtCore.Slot()
    def on_btn_answer_clicked(self):
        text = self.ui.text_answare.toPlainText()

        if text.strip() == '':
            self.ui.statusbar.showMessage('输入内容不能为空')
            return

        item = self.ui.list_wants.currentItem()
        if item is None:
            self.ui.statusbar.showMessage('请选择一个想法进行回复')
            return

        item_answares:list = item.data(QtCore.Qt.ItemDataRole.UserRole + 1)
        item_answares.append(text)
        item.setData(QtCore.Qt.ItemDataRole.UserRole + 1, item_answares)

        self.ui.text_answare.clear()
        self.on_list_wants_currentItemChanged(item, item)

    def append_answare_widget(self, index:int,  text: str):
        message = PopMessage(index, text)
        message.deleteMessage.connect(lambda index: self.on_answer_delete(index))
        message.copyMessage.connect(lambda text: self.on_answer_copy(text))
        self.ui.frame.layout().addWidget(message)
        QtCore.QTimer.singleShot(100, self.update_scrollbar)

    def on_answer_delete(self, index:int):
        item = self.ui.list_wants.currentItem()
        answers:list =  item.data(QtCore.Qt.ItemDataRole.UserRole + 1)
        answers.pop(index)
        item.setData(QtCore.Qt.ItemDataRole.UserRole + 1, answers)
        self.on_list_wants_currentItemChanged(item, item)

    def on_answer_copy(self, text: str):
        QtWidgets.QApplication.clipboard().setText(text)

    # def on_answer_menu_requested(self, pos: QtCore.QPoint):
    #     answer_menu = QtWidgets.QMenu()
    #     def on_revocation():
    #         item = self.ui.list_wants.currentItem()
    #         answers:list =  item.data(QtCore.Qt.ItemDataRole.UserRole + 1)
    #         answers.pop(self.sender().property('index'))
    #         item.setData(QtCore.Qt.ItemDataRole.UserRole + 1, answers)
    #         self.on_list_wants_currentItemChanged(item, item)
        
    #     answer_menu.addAction("撤回", on_revocation)
    #     answer_menu.exec(QtGui.QCursor.pos())

    def update_scrollbar(self):
        self.ui.scrollArea.verticalScrollBar().setValue(self.ui.scrollArea.verticalScrollBar().maximumHeight())

    def update_list_wants(self):
        self.ui.list_wants.clear()
        for want in self.wants:
            title = want['title']
            answers = want['answers']
            want = QtWidgets.QListWidgetItem(title)
            want.setData(QtCore.Qt.ItemDataRole.UserRole + 1, answers)
            self.ui.list_wants.addItem(want)

if __name__ == '__main__':  
    import sys
    app = QtWidgets.QApplication(sys.argv)
    widget = HumanWantsWindow()
    widget.setWindowTitle("想法测试器")
    widget.show()
    widget.move(QtGui.QGuiApplication.primaryScreen().availableGeometry().center() - widget.rect().center())
    sys.exit(app.exec())
